package com.newsnetwork.article.html.controller;

import com.mongodb.client.gridfs.GridFSBucket;
import com.newsnetwork.api.controller.article.ArticleHTMLControllerApi;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * @author: HuangDekai
 * @date: 2022/11/19 15:10
 * @version: 1.0
 * @since: jdk8
 * @description: 静态化文章业务的controller实现
 */
@RestController
public class ArticleHTMLController implements ArticleHTMLControllerApi {

    private static final Logger log = LoggerFactory.getLogger(ArticleHTMLController.class);

    @Autowired
    private GridFSBucket gridFSBucket;
    @Value("${freemarker.html.article}")
    private String articlePath;

    /**
     * 下载静态化页面
     *
     * @param articleId      文章id
     * @param articleMongoId 文章在MongoDB中对应的id
     * @return 状态码, 内部使用的接口, 不需要太复杂
     */
    @Override
    public Integer download(String articleId, String articleMongoId) throws FileNotFoundException {
        // 拼接文件路径
        String path = articlePath + File.separator + articleId + ".html";
        log.info("下载路径:{}", path);
        log.info("articleId={}, articleMongoId={}", articleId, articleMongoId);
        // 获取文件流
        File file = new File(path);
        // 创建输出流
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        // 执行下载
        gridFSBucket.downloadToStream(new ObjectId(articleMongoId), fileOutputStream);
        return HttpStatus.OK.value();
    }

    /**
     * 删除静态化页面
     *
     * @param articleId 文章id
     * @return 状态码
     */
    @Override
    public Integer delete(String articleId) throws FileNotFoundException {
        // 拼接最终文件的保存的地址
        String path = articlePath + File.separator + articleId + ".html";

        // 获取文件流，定义存放的位置和名称
        File file = new File(path);

        // 删除文件
        file.delete();

        return HttpStatus.OK.value();
    }
}
